<?php

function redirect($path_for_redirect) {
    header("Location: " . URL . $path_for_redirect);
}

function getId() {
    $url = addslashes(@$_GET['url']);
    $url = rtrim($url, '/');
    $url = explode('/', $url);
    return $url;
}

function getPage() {
    $url = addslashes(@$_GET['url']);
    $url = rtrim($url, '/');
    $url = explode('/', $url);
    return $url;
}
function GetData($page_name=NULL) {
    $urlparts = explode("/", $_SERVER['REQUEST_URI']);
	
    $key = array_search($page_name, $urlparts);
    $key = $key + 1;

    $urlparts2 = explode("?", @$urlparts[$key]);
    $urlparts3 = explode("&", @$urlparts2[1]);

    for ($i = 0; $i < count($urlparts3); $i++) {
        $urlparts4[] = explode("=", @$urlparts3[$i]);
        $key = $urlparts4[$i][0];
        $value = @$urlparts4[$i][1];
        $array[] = ($key);
        $array1[] = ($value);
        $query = array_combine($array, $array1);
    }
    return $query;
}

//use GET instead of $_GET
function GET($page_name)
	{
		$urlparts = explode("?", $_SERVER['REQUEST_URI']);
		$urlparts1 =explode('&',$urlparts[count($urlparts)-1]);
		$key = array_search($page_name, $urlparts1);
		$key=$key+1;
		for($i=0;$i<count($urlparts1);$i++)
		{
			$urlparts4[] = explode("=",	@$urlparts1[$i]);
			$key= $urlparts4[$i][0];
			$value= @$urlparts4[$i][1];
			$array[]= ($key);
			$array1[]= ($value);
			$query=array_combine ($array,$array1);
		}		
		return (isset($query[$page_name])) ? $query[$page_name] : false;
	}



function ActiveUrl($page) {
    $url = getId();
	$url=$url[count($url)-1];
    if ($url==$page) {
        echo 'class="active"';
    } 
}

function strip($value) {
    $value = stripslashes($value);
    $value = str_replace('+', ' ', $value);
    $value = str_replace('%28', '(', $value);
    $value = str_replace('%29', ')', $value);
    $value = str_replace('%27', "'", $value);
    $value = str_replace('%3C', "<", $value);
    $value = str_replace('%3E', ">", $value);
    $value = str_replace('%22', '"', $value);
    return $value;
}

function stripPlus($value)
{
	$value= str_replace('+',' ',$value);
	return $value;
}
function stripBracket($value)
{
	$value= str_replace('%28','(',$value);
	$value= str_replace('%29',')',$value);
	return $value;
}
function date_convert($date)
{
			$phpdate = strtotime( $date );
			return date( 'd-m-Y', $phpdate );
}

function if_edit($edit,$data)
{
	if($edit=='edit')
	{
		echo $data;
	}
}
function if_select($data,$comp_data)
{
	
		if($data==$comp_data)
		{
			return 'selected="selected"';
		}
	
}
function if_radio($data,$comp_data)
{
	
		if($data==$comp_data)
		{
			return 'checked';
		}
	
}
function query_maker($check)
{
	for($i=0;$i<count($check); $i++ )
		{
			$key[]=key($check);
			
			$quer[$i]=($key[$i]."='".addslashes($check[$key[$i]])."'");
			next($check);
		}
		return implode(',',$quer);
}
function query_maker_int($check)
{
	for($i=0;$i<count($check); $i++ )
		{
			$key[]=key($check);
			$quer[$i]=($key[$i]."=".addslashes($check[$key[$i]])."");
			next($check);
		}
		
		return implode(',',$quer);
}
function insert_maker($check)
{
	for($i=0;$i<count($check); $i++ )
		{
			$key[]=key($check);
			
			$quer[$i]=($key[$i]);
			$value[$i]=("'".addslashes($check[$key[$i]])."'");
			next($check);
		}
		$new_insert="( ".implode(',',$quer)." ) VALUES (".implode(',',$value).")";
		return $new_insert;
}
function check_maker($check)
{
	for($i=0;$i<count($check); $i++ )
		{
			$key[]=key($check);
			$quer[$i]=($key[$i]."='".addslashes($check[$key[$i]])."'");
			next($check);
		}
		return implode(' and ',$quer);
}

function truncate($text, $length, $suffix ='', $isHTML = true) {
    $i = 0;
    $simpleTags=array('br'=>true,'hr'=>true,'input'=>true,'image'=>true,'link'=>true,'meta'=>true);
    $tags = array();
    if($isHTML){
        preg_match_all('/<[^>]+>([^<]*)/', $text, $m, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
        foreach($m as $o){
            if($o[0][1] - $i >= $length)
                break;
            $t = substr(strtok($o[0][0], " \t\n\r\0\x0B>"), 1);
            // test if the tag is unpaired, then we mustn't save them
            if($t[0] != '/' && (!isset($simpleTags[$t])))
                $tags[] = $t;
            elseif(end($tags) == substr($t, 1))
                array_pop($tags);
            $i += $o[1][1] - $o[0][1];
        }
    }

    // output without closing tags
    $output = substr($text, 0, $length = min(strlen($text),  $length + $i));
    // closing tags
    $output2 = (count($tags = array_reverse($tags)) ? '</' . implode('></', $tags) . '>' : '');

    // Find last space or HTML tag (solving problem with last space in HTML tag eg. <span class="new">)
  
	$splitted = preg_split('/<.*>| /', $output, -1, PREG_SPLIT_OFFSET_CAPTURE);
	$last_item = end($splitted);
	$pos = end($last_item);
    // Append closing tags to output
    $output.=$output2;

    // Get everything until last space
    $one = substr($output, 0, $pos);
    // Get the rest
    $two = substr($output, $pos, (strlen($output) - $pos));
    // Extract all tags from the last bit
    preg_match_all('/<(.*?)>/s', $two, $tags);
    // Add suffix if needed
    if (strlen($text) > $length) { $one .= $suffix; }
    // Re-attach tags
    $output = $one . implode($tags[0]);

    //added to remove  unnecessary closure
    $output = str_replace('</!-->','',$output); 

    return $output;
}

function authentication($page="secure")
{
	if($page=="secure"){
		if(!isset($_SESSION['login']) || !isset($_SESSION['login_code']))
		{
			header('Location: '.URL.'logout.php');
		}
	}
	else
	{
		if(isset($_SESSION['login']) && isset($_SESSION['login_code']))
		{
			header("Location: ".URL."home/");
		} 
	}
}

   function pagination($query, $per_page = 10,$page = 1, $url = '?',$old_data){   
        
    	$query = "SELECT COUNT(*) as `num` FROM {$query}";
    	$row = mysql_fetch_array(mysql_query($query));
    	$total = $row['num'];
        $adjacents = "2"; 

    	$page = ($page == 0 ? 1 : $page);  
    	$start = ($page - 1) * $per_page;								
		
    	$prev = $page - 1;							
    	$next = $page + 1;
        $lastpage = ceil($total/$per_page);
    	$lpm1 = $lastpage - 1;
    	
    	$pagination = "";
    	if($lastpage > 1)
    	{	
    		$pagination .= "<ul class='pagination'>";
                    $pagination .= "<li class='details'>Page $page of $lastpage</li>";
    		if ($lastpage < 7 + ($adjacents * 2))
    		{	
    			for ($counter = 1; $counter <= $lastpage; $counter++)
    			{
    				if ($counter == $page)
    					$pagination.= "<li><a class='current'>$counter</a></li>";
    				else
    					$pagination.= "<li><a href='{$url}".$old_data."&page=$counter'>$counter</a></li>";					
    			}
    		}
    		elseif($lastpage > 5 + ($adjacents * 2))
    		{
    			if($page < 1 + ($adjacents * 2))		
    			{
    				for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
    				{
    					if ($counter == $page)
    						$pagination.= "<li><a class='current'>$counter</a></li>";
    					else
    						$pagination.= "<li><a href='{$url}".$old_data."&page=$counter'>$counter</a></li>";					
    				}
    				$pagination.= "<li class='dot'>...</li>";
    				$pagination.= "<li><a href='{$url}".$old_data."&page=$lpm1'>$lpm1</a></li>";
    				$pagination.= "<li><a href='{$url}".$old_data."&page=$lastpage'>$lastpage</a></li>";		
    			}
    			elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))
    			{
    				$pagination.= "<li><a href='{$url}".$old_data."&page=1'>1</a></li>";
    				$pagination.= "<li><a href='{$url}".$old_data."&page=2'>2</a></li>";
    				$pagination.= "<li class='dot'>...</li>";
    				for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
    				{
    					if ($counter == $page)
    						$pagination.= "<li><a class='current'>$counter</a></li>";
    					else
    						$pagination.= "<li><a href='{$url}".$old_data."&page=$counter'>$counter</a></li>";					
    				}
    				$pagination.= "<li class='dot'>..</li>";
    				$pagination.= "<li><a href='{$url}".$old_data."&page=$lpm1'>$lpm1</a></li>";
    				$pagination.= "<li><a href='{$url}".$old_data."&page=$lastpage'>$lastpage</a></li>";		
    			}
    			else
    			{
    				$pagination.= "<li><a href='{$url}".$old_data."&page=1'>1</a></li>";
    				$pagination.= "<li><a href='{$url}".$old_data."'&page=2'>2</a></li>";
    				$pagination.= "<li class='dot'>..</li>";
    				for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++)
    				{
    					if ($counter == $page)
    						$pagination.= "<li><a class='current'>$counter</a></li>";
    					else
    						$pagination.= "<li><a href='{$url}".$old_data."&page=$counter'>$counter</a></li>";					
    				}
    			}
    		}
    		
    		if ($page < $counter - 1){ 
    			$pagination.= "<li><a href='{$url}".$old_data."&page=$next'>Next</a></li>";
                $pagination.= "<li><a href='{$url}".$old_data."&page=$lastpage'>Last</a></li>";
    		}else{
    			$pagination.= "<li><a class='current'>Next</a></li>";
                $pagination.= "<li><a class='current'>Last</a></li>";
            }
    		$pagination.= "</ul>\n";		
    	}
    
    
        return $pagination;
    } 

function getCategory($catID)
{
	$sql=new sql();
	$catIDRow=$sql->fetch('category', array('uid'=>$catID));
	return $catIDRow['text'];
}
function getMenu($ManuID)
{
	$sql=new sql();
	$catIDRow=$sql->fetch('menu', array('uid'=>$ManuID));
	
	return $catIDRow['label'];
}
function getAdmin($adminID)
{
	$sql=new sql();
	$adminIDRow=$sql->fetch('admin', array('uid'=>$adminID));
	return $adminIDRow['username'];
}
function permalink($pageId)
{
	$sql=new sql();
	$pageTitle=$sql->fetch('page', array('uid'=>$pageId));
	
	$permalink=str_replace(' ','-',strtolower(trim($pageTitle['heading'])));
	
	$check=$sql->check('page',array("permalink"=>$permalink));
	if($check)
	{
		$permalink=$permalink.'-'.rand(10,99);
	}
	return 	$permalink;
}
function getModule($moduleID)
{
	$sql=new sql();
	$sql->connect();
	$fetch=$sql->check('modules',array('uid'=>$moduleID,'active'=>'1'));
	if($fetch)
	{
		$module= $sql->fetch('modules',array('uid'=>$moduleID,'active'=>'1'));
		echo magicKeyword($module['source']);
	}
}
function magicKeyword($data)
{
		$MAIL = MAIL;
		$URL = URL;
		$SITENAME = SITENAME;
		$VIEW = VIEW;	
		$TEMPLATE = TEMPLATE;	

		return preg_replace('/\{([A-Z]+)\}/e', "$$1", $data);
}
//Template Works
function fnGetMeta()
{
	include(BASEURL.VIEW.'include/meta.php');
}
function fnGetHeader()
{
	include(BASEURL.VIEW.'include/header.php');
}
function fnGetMenu()
{
	include(BASEURL.VIEW.'include/menu.php');
}
function fnGetFooter()
{
	include(BASEURL.VIEW.'include/footer.php');
}
function fnGetSidebar()
{
	include(BASEURL.VIEW.'include/sidebar.php');
}
function fnGetSlider()
{
	include(BASEURL.VIEW.'include/slider.php');
}
?>